import { reactive, ref } from "vue";

export default function useSearch({ rules = {}, defaultData = {}, responseKey }) {
  const formData = reactive({
    pageSize: 10,
    pageNum: 1,
    ...defaultData
  });
  const tableData = reactive({
    list: [],
    total: 0,
    originData: null
  });
  const searchFormRef = ref();
  const searchFormRules = reactive(rules);
  /**
   * @desc 重载数据
   */
  const reloadData = () => {
    Object.assign(formData, defaultData);
    for (const argumentsKey in formData) {
      if(!defaultData.hasOwnProperty(argumentsKey)) {
      formData[argumentsKey] = undefined;

      }
    }
    formData.pageNum = 1;
    formData.pageSize = 10;
    if (searchFormRef.value) {
      searchFormRef.value.clearValidate();
    }
  };
  /**
   * @desc 重置数据
   * */
  const resetData = async ({ api, sendData, autoSetrowSpans = false, spankey = "id" }) => {
    for (const key in formData) {
      if (Object.prototype.hasOwnProperty.call(formData, key)) {
        formData[key] = undefined;
      }
    }
    reloadData();
    if (searchFormRef.value) {
      setTimeout(() => {
        searchFormRef.value.clearValidate();
      }, 100);
    }
    loadData({
      api,
      sendData,
      autoSetrowSpans,
      spankey
    });
  };
  /**
   * @desc 查询
   */
  const loadData = async ({ api, sendData, autoSetrowSpans = false, spankey = "id" }) => {
    return new Promise(async (resolve, reject) => {
      if (Object.keys(searchFormRules).length) {
        if (!searchFormRef.value) {
          reject(false);
          return;
        }
        await searchFormRef.value.validate();
      }

      try {
        const data = await api(sendData);
        // 根据数据结构切换
        console.info("data", data);
        tableData.list = getNestedData(data, responseKey.list);
        tableData.total = Number(getNestedData(data, responseKey.total));
        console.log("tableData", tableData);
        tableData.originData = data;
        if (autoSetrowSpans) {
          setrowspans(spankey);
        }

        resolve(data);
      } catch (error) {
        reject(error);
        if (searchFormRef.value) {
          searchFormRef.value.clearValidate();
        }
        return error;
      }
    });
  };

  /**
   * @desc 合并单元格时区分行数据(可选) 通过classStripe字段
   */
  function setrowspans(spankey = "id") {
    // 先给所有的数据都加一个v.rowspan = 1
    tableData.list.forEach(v => {
      v.rowspan = 1;
      v.classStripe = false;
    });
    console.info(tableData.list);
    // debugger
    // 双层循环
    for (let i = 0; i < tableData.list.length; i++) {
      // 内层循环，上面已经给所有的行都加了v.rowspan = 1
      // 这里进行判断
      // 如果当前行的id和下一行的id相等
      // 就把当前v.rowspan + 1
      // 下一行的v.rowspan - 1
      for (let j = i + 1; j < tableData.list.length; j++) {
        if (tableData.list[i][spankey] === tableData.list[j][spankey]) {
          tableData.list[i].rowspan++;
          tableData.list[j].rowspan--;
          tableData.list[j].classStripe = tableData.list[i].classStripe;
        } else {
          tableData.list[j].classStripe = !tableData.list[i].classStripe;
        }
      }
      // 这里跳过已经重复的数据
      i = i + tableData.list[i].rowspan - 1;
    }
  }

  function getNestedData(obj, path) {
    let paths = path.split(".");

    let current = obj;

    for (let i = 0; i < paths.length; i++) {
      if (current[paths[i]] === undefined) {
        return undefined;
      } else {
        current = current[paths[i]];
      }
    }

    return current;
  }

  return {
    formData,
    loadData,
    resetData,
    tableData,
    reloadData,
    searchFormRef,
    searchFormRules
  };
}
